import api from '../request/vmeitime-http/index.js'
import Vue from 'vue';
//#ifdef MP-WEIXIN
import share from './share.js'
//#endif
const mixin = {
    data() {
        return {
            __before: null,
            __after: null,
            debug: false,
            env: '',
            token: '',
            scrollTopValue: 0,
            isWx: false,
            version: '1.1.8'
        };
    },
    onPageScroll(e) {
        this.scrollTopValue = e.scrollTop;
    },
    onLoad() {
        this.about();

        // #ifndef VUE2
        this.console("当前插件只支持vue2！！！", "color: red", "warn");
        // #endif

        // #ifdef MP-WEIXIN
        let envVersion = wx.getAccountInfoSync().miniProgram.envVersion;
        switch (envVersion) {
            case 'develop':
                this.env = '开发环境'
                this.debug = true;
                break;
            case 'trial':
                this.env = '测试环境'
                break;
            case 'release':
                this.env = '生产环境'
                break;
            default:
                this.env = '未知环境'
                break;
        }
        console.log(process.env.NODE_ENV, envVersion, this.structureId);
        // #endif

        //#ifdef H5
        let status = navigator.userAgent.toLowerCase();
        if (status.match(/MicroMessenger/i) == "micromessenger") {
            this.isWx = true;
        } else {
            this.isWx = false;
        }
        console.log(this.isWx ? '微信浏览器' : '普通浏览器');
        //#endif

        uni.getSystemInfo({
            success: e => {
                this.initSize(e);
            }
        })
    },
    methods: {

        // ********************** 网络请求 START **********************
        /**
         * get
         * @param {Object} url
         * @param {Object} data
         * @param {Object} headers
         * @param {Object} success
         * @param {Object} fail
         */
        get: function(url, data, headers, success, fail) {
            if (!fail) {
                fail = () => {
                    this.msg("网络请求失败");
                }
            }
            if (!headers) {
                headers = {};
            }
            if (this.__before != null) {
                this.__before();
                this.__before = null;
            }
            uni.request({
                url: url,
                data: data,
                method: "GET",
                dataType: "json",
                header: headers,
                success: (res) => {
                    success(res.data);
                },
                fail: fail,
                complete: () => {
                    if (this.__after != null) {
                        this.__after();
                        this.__after = null;
                    }
                }
            });
        },
        /**
         * post
         * @param {Object} url
         * @param {Object} data
         * @param {Object} contentType
         * @param {Object} headers
         * @param {Object} success
         * @param {Object} fail
         */
        post: function(url, data, contentType, headers, success, fail) {
            if (!fail) {
                fail = () => {
                    this.msg("网络请求失败");
                }
            }
            if (!headers) {
                headers = {};
            }
            if (!contentType) {
                contentType = 'form';
            }
            if (this.__before != null) {
                this.__before();
                this.__before = null;
            }
            switch (contentType) {
                case "form":
                    headers['content-type'] = 'application/x-www-form-urlencoded';
                    break;
                case "json":
                    headers['content-type'] = 'application/json';
                    break;
                default:
                    headers['content-type'] = 'application/x-www-form-urlencoded';
            }
            uni.request({
                url: url,
                data: data,
                method: "POST",
                dataType: "json",
                header: headers,
                success: (res) => {
                    success(res.data);
                },
                fail: fail,
                complete: () => {
                    if (this.__after != null) {
                        this.__after();
                        this.__after = null;
                    }
                }
            });
        },
        /**
         * 请求前置函数
         * @param {Object} func
         */
        setBefore: function(func) {
            this.__before = func;
        },
        /**
         * 请求后置函数
         * @param {Object} func
         */
        setAfter: function(func) {
            this.__after = func;
        },
        // **********************  网络请求 END  **********************

        // ********************** 数据缓存 START **********************
        setStorage: function(data, debug = false) {
            try {
                for (let k in data) {
                    uni.setStorageSync(k, data[k]);
                }
                return true;
            } catch (e) {
                if (debug) {
                    return this.showToast(JSON.stringify(e));
                }
                return false;
            }
        },
        getStorage: function(keyName, debug = false) {
            try {
                var tmpVal = uni.getStorageSync(keyName);
                if (tmpVal == '') {
                    return false;
                }
                return tmpVal;
            } catch (e) {
                if (debug) {
                    return this.showToast(JSON.stringify(e));
                }
                return false;
            }
        },
        removeStorage: function(keyName) {
            try {
                uni.removeStorageSync(keyName);
                return true;
            } catch (e) {
                return false;
            }
        },
        clearStorage: function() {
            try {
                uni.clearStorageSync();
            } catch (e) {}
        },
        // **********************  数据缓存 END  **********************

        // ********************** 图片相关 START **********************
        chooseImgs: function(sets, success, fail, complete) {
            if (!sets.count) {
                sets.count = 1;
            }
            if (!sets.sizeType) {
                sets.sizeType = ['original', 'compressed'];
            }
            if (!sets.sourceType) {
                sets.sourceType = ['album', 'camera'];
            }
            uni.chooseImage({
                count: sets.count, //默认9
                sizeType: sets.sizeType, //可以指定是原图还是压缩图，默认二者都有
                sourceType: sets.sourceType, //从相册选择
                success: (res) => {
                    success(res.tempFilePaths);
                },
                fail: (e) => {
                    if (fail) {
                        fail(e);
                    }
                },
                complete: (e) => {
                    if (complete) {
                        complete(e);
                    }
                }
            });
        },
        getImageInfo: function(imgUrl, success, fail, complete) {
            uni.getImageInfo({
                src: imgUrl,
                success: function(info) {
                    success(info);
                },
                fail: (e) => {
                    if (fail) {
                        fail(e);
                    }
                },
                complete: (e) => {
                    if (complete) {
                        complete(e);
                    }
                }
            });
        },
        previewImage: function(value, currentIndex = 0) {
            if (this.isArray(value))
                // 预览多张图片
                uni.previewImage({
                    urls: value,
                    current: currentIndex
                });
            else {
                // 预览一张图片
                let urls = [value];
                uni.previewImage({
                    urls: urls,
                    current: currentIndex
                })
            }
        },
        // **********************  图片相关 END  **********************

        // ********************** 消息弹框 START **********************
        showToast(message, timeout = 2000) {
            uni.showToast({
                title: message,
                icon: 'none',
                duration: timeout
            });
            return true;
        },
        showLoading: function(title = '加载中...') {
            uni.showLoading({
                title: title,
                mask: true
            });
        },
        // **********************  消息弹框 END  **********************

        // ********************** 其它 START **********************
        about() {
            this.console(
                ['\n', `DferTools V${this.version}`, 'http://www.dfer.site/', '\n'],
                [null, 'color: #ffffff; background: #000000; padding:5px 0; border-radius: 5px;',
                    'color: #ffffff; background: #000000; padding:5px 0; border-radius: 5px;', null
                ]
            )
        },
        /**
         * 控制台输出字符串
         * @param {Object} data 文本
         * @param {Object} style 样式
         * @param {Object} type 类型
         */
        console(data, style = null, type = "log") {
            style = style ?? '';
            let text_list = this.isString(data) ? [data] : data;
            let style_list = this.isString(style) ? [style] : style;
            let text = `%c ${text_list.join(' %c ')}`;
            let args = [];
            args.push(text);
            args = args.concat(style_list);
            switch (type) {
                case 'log':
                    console.log.apply(console, args);
                    break;
                case 'warn':
                    console.warn.apply(console, args);
                    break;
                case 'error':
                    console.error.apply(console, args);
                default:
                    break;
            }
        },
        /**
         * 动态设置当前页面的标题
         * @param {Object} title
         */
        setNavTitle(title) {
            uni.setNavigationBarTitle({
                title,
                fail(err) {
                    console.log(err)
                }
            })
        },
        /**
         * 打开地图
         * @param {Object} latitude
         * @param {Object} longitude
         */
        openLocation(latitude, longitude) {
            uni.openLocation({
                latitude: Number(latitude),
                longitude: Number(longitude),
                success: function() {},
                fail(err) {}
            });
        },
        /**
         * 根据对象id获取对象内容
         * @param {Object} obj
         * @param {Object} id
         */
        getObjectById(obj, id) {
            for (const key in obj) {
                if (obj[key].id === id) {
                    return obj[key];
                }
            }
            return null;
        },
        getLabelByValue(obj, value) {
            console.log(obj, value);
            for (const key in obj) {
                if (obj[key].value === value) {
                    return obj[key].label;
                }
            }
            return null;
        },
        getTextByValue(obj, value) {
            for (const key in obj) {
                if (obj[key].value == value) {
                    return obj[key].text;
                }
            }
            return null;
        },
        /**
         * 将所有的 null 和 undefined 替换为空字符串
         * @param {Object} data
         */
        cleanFormData(data) {
            const cleanedData = {
                ...data
            };
            for (let key in cleanedData) {
                if (cleanedData[key] == null) { // 同时判断 null 和 undefined
                    cleanedData[key] = '';
                }
            }
            return cleanedData;
        },
        /**
         * 将所有的 null 和 undefined 替换为`--`
         * @param {Object} data
         */
        showEmptyData(data, debug = false) {
            for (let key in data) {
                if (debug)
                    console.log(data[key]);
                if (data[key] == null || data[key] == '') { // 同时判断 null 和 undefined
                    data[key] = '--';
                }
            }
            return data;
        },
        /**
         * 存储设备信息
         * @param {Object} e
         */
        initSize(e) {
            const systemInfo = e;
            let navigationBarHeight;
            let custom = {};

            // #ifdef MP
            custom = wx.getMenuButtonBoundingClientRect();
            navigationBarHeight = custom.bottom + custom.top - e.statusBarHeight * 2;
            Vue.prototype.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
            // #endif

            // #ifndef MP
            custom = {
                height: 36,
                width: 88
            };
            navigationBarHeight = 44;
            // #endif


            systemInfo.custom = custom;
            systemInfo.navigationBarHeight = navigationBarHeight;
            Vue.prototype.systemInfo = systemInfo;

        },
        stringToBoolean(str) {
            if (typeof str === 'string') {
                str = str.toLowerCase().trim();
                return str === 'true' ||
                    str === '1' ||
                    str === 'yes' ||
                    str === 'on';
            } else {
                return str;
            }
        },
        /**
         * 页面跳转
         * @param {Object} url
         * @param {Object} type
         * @param {Object} success
         * @param {Object} fail
         * @param {Object} complete
         */
        navigate: function(url, type, success, fail, complete) {
            if (!type) {
                type = 'navigateTo';
            }
            if (!success) {
                success = function() {};
            }
            if (!fail) {
                fail = function() {};
            }
            if (!complete) {
                complete = function() {};
            }
            switch (type) {
                case 'navigateTo':
                    uni.navigateTo({
                        url: url,
                        success: success,
                        fail: fail,
                        complete: complete
                    });
                    break;
                case 'redirectTo':
                    uni.redirectTo({
                        url: url,
                        success: success,
                        fail: fail,
                        complete: complete
                    });
                    break;
                case 'switchTab':
                    uni.switchTab({
                        url: url,
                        success: success,
                        fail: fail,
                        complete: complete
                    });
                    break;
                case 'reLaunch':
                    uni.reLaunch({
                        url: url,
                        success: success,
                        fail: fail,
                        complete: complete
                    });
                    break;
            }
        },
        /**
         * 返回
         * @param {Object} delta
         */
        back: function(delta) {
            if (!delta) {
                delta = 1;
            }
            uni.navigateBack({
                delta: delta
            });
        },
        confirm(title, fn, params) {
            uni.showModal({
                content: title,
                confirmText: "确定",
                cancelText: "取消",
                cancelColor: "#71ADF5",
                confirmColor: "#71ADF5",
                success: function(res) {
                    if (res.confirm) {
                        fn(params);
                    }
                }
            })
        },
        /**
         * 将对象中的所有值转换为整数
         * @param {Object} value
         */
        convertObjectValuesToInt(obj) {
            return Object.fromEntries(
                Object.entries(obj).map(([key, value]) => [key, parseInt(value) || 0])
            );
        },
        getDate(type) {
            const date = new Date();
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();

            if (type === 'start') {
                year = year - 60;
            } else if (type === 'end') {
                year = year + 2;
            }
            month = month > 9 ? month : '0' + month;
            day = day > 9 ? day : '0' + day;
            return `${year}-${month}-${day}`;
        },
        isString(value) {
            if (typeof value === 'string') {
                return true;
            }
            return false;
        },
        isArray(value) {
            if (Array.isArray(value)) {
                return true;
            }
            return false;
        },
        /**
         * @param {Object} str
         * @return {String} 标准化的小写且无前后空格的字符串
         */
        lowerTrim(str) {
            return str.toLowerCase().trim();
        },
        /**
         * 拆分URL地址和参数，并将参数转换为数组形式
         * @param {Object} url
         */
        parseUrlParams(url) {
            const [path, queryString] = url.split('?');
            const params = {};
            if (queryString) {
                const pairs = queryString.split('&');
                for (const pair of pairs) {
                    const [key, value] = pair.split('=');
                    const numValue = Number(value);
                    params[key] = isNaN(numValue) ? value : numValue;
                }
            }
            return {
                path: path,
                params: params
            };
        },
        /**
         * json字符串和对象自动互转
         * @param {Object} data
         */
        jsonStringAndObject(data) {
            let result = null;
            if (typeof data === 'string') {
                result = JSON.parse(data);
            } else {
                result = JSON.stringify(data);
            }
            return result;
        },
        /**
         * 获取子项内容，不存在则返回默认值
         * 支持嵌套属性
         * eg：
         * console.log(hasNestedProperty(data, 'user.profile.name',123)); 
         * console.log(hasNestedProperty(data, 'user')); 
         * @param {Object} obj
         * @param {Object} path
         */
        getProperty(obj, path, defaultValue = false) {
            if (!obj || typeof obj !== 'object') return defaultValue;

            const keys = Array.isArray(path) ? path : path.split('.');
            let current = obj;

            for (const key of keys) {
                if (!current || typeof current !== 'object' || !(key in current)) {
                    return defaultValue;
                }
                current = current[key];
            }

            return current;
        },
        /**
         * 设置tabBar提示
         * @param {Object} index 编号
         * @param {Object} text 内容
         * @param {Object} type 类型
         */
        tabBar(index, text = null, type = 'setTabBarBadge') {
            switch (type) {
                case 'setTabBarBadge':
                    uni.setTabBarBadge({
                        index: index,
                        text: String(text)
                    });
                    break;
                case 'removeTabBarBadge':
                    uni.removeTabBarBadge({
                        index: index
                    });
                    break;
                case 'showTabBarRedDot':
                    uni.showTabBarRedDot({
                        index: index
                    });
                    break;
                case 'hideTabBarRedDot':
                    uni.hideTabBarRedDot({
                        index: index
                    });
                    break;
                default:
                    break;
            }
        }
        // **********************  其它 END  **********************

    }
}

export default {
    install(Vue, options) {
        Vue.prototype.$dfer_api = api
        Vue.mixin(mixin)

        //#ifdef MP-WEIXIN
        Vue.mixin(share)
        //#endif



    }
}